import React, { useState, useRef, useEffect } from 'react';
import { Table, Button, Input, message, Alert } from 'antd';
import Notification from '../../../components/Notification';
const WheelDraw = () => {
  const [segments, setSegments] = useState([]);
  const [percentageSum, setPercentageSum] = useState(0);
  const [isSpinning, setIsSpinning] = useState(false);
  const [stopTimeout, setStopTimeout] = useState(null);
  const [winningSegment, setWinningSegment] = useState(null);
  const [rotationAngle, setRotationAngle] = useState(0);

  const canvasRef = useRef(null);
  let wheel;

  useEffect(() => {
    drawWheel();
  }, [segments, rotationAngle]);

  const drawWheel = () => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    const radius = Math.min(canvas.width, canvas.height) / 2;
    const center = { x: canvas.width / 2, y: canvas.height / 2 };
    let currentAngle = 0;

    segments.forEach(segment => {
      ctx.beginPath();
      ctx.moveTo(center.x, center.y);
      ctx.arc(
        center.x,
        center.y,
        radius,
        currentAngle,
        currentAngle + 2 * Math.PI * (segment.percentage / 100)
      );
      ctx.closePath();
      ctx.fillStyle = segment.color;
      ctx.fill();
      currentAngle += 2 * Math.PI * (segment.percentage / 100);
    });

    drawPointer();
  };

  const drawPointer = () => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');

    const radius = Math.min(canvas.width, canvas.height) / 2;
    const center = { x: canvas.width / 2, y: canvas.height / 2 };

    ctx.save();
    ctx.translate(center.x, center.y);
    ctx.rotate(rotationAngle);
    ctx.translate(-center.x, -center.y);

    ctx.beginPath();
    ctx.moveTo(center.x, center.y - radius);
    ctx.lineTo(center.x - 10, center.y - radius + 30);
    ctx.lineTo(center.x + 10, center.y - radius + 30);
    ctx.closePath();
    ctx.fillStyle = '#000000';
    ctx.fill();
    ctx.restore();
  };

  const start = () => {
    if (percentageSum !== 100) {
      message.error('百分比总和必须为100%');
      return;
    }
    setIsSpinning(true);
    wheel = setInterval(() => {
      setRotationAngle(prevAngle => prevAngle + (2 * Math.PI) / 360);
    }, 1000 / 60);

    const randomStopTime = Math.floor(Math.random() * 7000) + 1000;
    setStopTimeout(
      setTimeout(() => {
        stop();
      }, randomStopTime)
    );
  };

  const stop = () => {
    clearTimeout(stopTimeout);
    setIsSpinning(false);
    clearInterval(wheel);
    const winner = getWinningSegment();
    setWinningSegment(winner);
    message.success(`中奖项目：${winner.text}`);
  };
  const getWinningSegment = () => {
    const winningAngle = (2 * Math.PI - rotationAngle) % (2 * Math.PI); // 计算当前旋转角度相对于起始位置的角度
    const totalPercentage = segments.reduce(
      (total, segment) => total + segment.percentage,
      0
    );
    let currentAngle = 0;

    for (const segment of segments) {
      currentAngle += (segment.percentage / totalPercentage) * 2 * Math.PI;
      if (winningAngle <= currentAngle) {
        return segment;
      }
    }
    return segments[segments.length - 1];
  };

  // ... the rest of the code remains the same

  const columns = [
    {
      title: '项目',
      dataIndex: 'text',
      render: (text, record) => (
        <Input
          value={text}
          onChange={e => {
            const newSegments = segments.map(segment =>
              segment.key === record.key
                ? { ...segment, text: e.target.value }
                : segment
            );
            setSegments(newSegments);
          }}
        />
      ),
    },
    {
      title: '百分比',
      dataIndex: 'percentage',
      render: (percentage, record) => (
        <Input
          type='number'
          min={0}
          max={100}
          value={percentage}
          onChange={e => {
            const newPercentage = parseInt(e.target.value, 10);
            const newSegments = segments.map(segment =>
              segment.key === record.key
                ? { ...segment, percentage: newPercentage }
                : segment
            );
            setSegments(newSegments);
            setPercentageSum(
              newSegments.reduce((sum, segment) => sum + segment.percentage, 0)
            );
          }}
        />
      ),
    },
    {
      title: '颜色',
      dataIndex: 'color',
      render: (color, record) => (
        <Input
          type='color'
          value={color}
          onChange={e => {
            const newSegments = segments.map(segment =>
              segment.key === record.key
                ? { ...segment, color: e.target.value }
                : segment
            );
            setSegments(newSegments);
          }}
        />
      ),
    },
    {
      title: '',
      dataIndex: 'operation',
      render: (_, record) => (
        <Button
          type='link'
          onClick={() => {
            const newSegments = segments.filter(
              segment => segment.key !== record.key
            );
            setSegments(newSegments);
            setPercentageSum(
              newSegments.reduce((sum, segment) => sum + segment.percentage, 0)
            );
          }}>
          删除
        </Button>
      ),
    },
  ];

  return (
    <div>
      <Table
        dataSource={segments}
        columns={columns}
        pagination={false}
        footer={() => (
          <Button
            type='dashed'
            onClick={() => {
              const newSegment = {
                key: Date.now(),
                text: '',
                percentage: 0,
                color: '#000000',
              };
              setSegments([...segments, newSegment]);
            }}>
            添加项目
          </Button>
        )}
      />

      <p>总百分比: {percentageSum}%</p>

      <div style={{ display: 'flex' }}>
        <div>
          <canvas
            ref={canvasRef}
            width='500'
            height='500'
          />
        </div>
        <div>
          <Alert
            style={{ width: '100%', height: '100px' }}
            message={'使用说明'}
            description={
              <>
                <span>"请自动添加项目,项目百分比和为100%才能开始"</span>
                <br />
                <span>点击开始后，转盘会在七秒内随机停下</span>
              </>
            }
          />
        </div>
        <div>
          <h3>中奖项目:</h3>
          {winningSegment && <p>{winningSegment.text}</p>}
        </div>
      </div>

      <Button
        onClick={start}
        disabled={isSpinning || percentageSum !== 100}>
        开始
      </Button>
    </div>
  );
};

export default WheelDraw;
